package com.robcity.platform.application;

import cn.hutool.json.JSONUtil;
import com.robcity.platform.dto.RobotLocationInfoSaveDTO;
import com.robcity.platform.param.RobotReqCommon;
import com.robcity.platform.param.RobotUploadReq;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Description
 * @Author zhangsong
 * @Date 2024/8/8
 **/
public class UdpRequestTest {
    //定义客户端ip
    private static final String SERVER_HOSTNAME = "127.0.0.1";
    // 服务器端口
    private static final int SERVER_PORT = 51000;
    // 本地发送端口
    private static final int LOCAL_PORT = 8888;
    public static void main(String[] args) {
        try {
            // 1，创建udp服务。通过DatagramSocket对象。
            DatagramSocket socket = new DatagramSocket(LOCAL_PORT);
            // 2，确定数据，并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress
            // address, int port)
//            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 50000);
//            DatagramPacket dp   =datagramPacket("hello",inetSocketAddress);
            RobotReqCommon robotReqCommon=new RobotReqCommon();
            robotReqCommon.setMsgType(1);
            RobotLocationInfoSaveDTO robotLocationInfoDTO = new RobotLocationInfoSaveDTO();
            robotLocationInfoDTO.setRob_id("123456");
            robotLocationInfoDTO.setTimeStemp("12345");
            robotLocationInfoDTO.setAlt(BigDecimal.valueOf(123.123));
            robotLocationInfoDTO.setCurCmd("commond1");
            robotLocationInfoDTO.setLat(BigDecimal.valueOf(123.123));
            robotLocationInfoDTO.setLon(BigDecimal.valueOf(123.123));
            robotLocationInfoDTO.setBatLife("10");
            RobotUploadReq req = new RobotUploadReq();
            req.setCommon(robotReqCommon);
            req.setData(robotLocationInfoDTO);
            String json =  JSONUtil.toJsonStr(req);
            // address, int port)
            byte[] buf = json.getBytes();
            DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(SERVER_HOSTNAME),
                    SERVER_PORT);
            // 3，通过socket服务，将已有的数据包发送出去。通过send方法。
            socket.send(dp);
            // 4，关闭资源。
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 组装数据包
     *
     * @param msg               消息串
     * @param inetSocketAddress 服务器地址
     * @return DatagramPacket
     */
//    public static DatagramPacket datagramPacket(String msg, InetSocketAddress inetSocketAddress) {
//        DatagramPacket datagramPacket;
//        ByteBuf dataBuf = Unpooled.copiedBuffer(msg, StandardCharsets.UTF_8);
//        datagramPacket = new DatagramPacket(dataBuf, inetSocketAddress);
//        return datagramPacket;
//    }


}
